package ch.ethz.inf.shop;

import java.io.IOException;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import ch.ethz.inf.shop.model.DatastoreInterface;
import ch.ethz.inf.shop.model.Recipe;
import ch.ethz.inf.shop.util.html.BeanTableHelper;

/**
 * Servlet implementation class of Recipes search page
 */
@WebServlet(description = "Page that displays the recipes", urlPatterns = { "/Recipes" })
public final class RecipesServlet extends HttpServlet {

	private static final long serialVersionUID = 1L;
	private final DatastoreInterface dbInterface = new DatastoreInterface();

	/**
	 * @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse
	 *      response)
	 */
	@Override
	protected final void doGet(final HttpServletRequest request, final HttpServletResponse response) throws ServletException, IOException {

		final HttpSession session = request.getSession(true);

		/*******************************************************
		 * Construct a table to present all our results
		 */
		final BeanTableHelper<Recipe> table = new BeanTableHelper<Recipe>("recipes", "productsTable", Recipe.class);

		table.addBeanColumn("<a href=\"Recipes?orderBy=name\">Name</a>", "name");
		table.addBeanColumn("<a href=\"Recipes?orderBy=price\">Cost</a>", "costOfIngredients");
		/*
		 * Column 4: This is a special column. It adds a link to view the
		 * Product. We need to pass the product identifier to the url.
		 */
		table.addLinkColumn("", "<img src=\"images/document-open.png\" alt=\"View Recipe\"/>", "Recipe?recipeId=", "recipeId");

		String orderBy = request.getParameter("orderBy");
		table.addObjects(this.dbInterface.getRecipes(orderBy));

		// Pass the table to the session. This will allow the respective jsp
		// page
		// to display the table.
		session.setAttribute("recipes", table);

		// Finally, proceed to the Products.jsp page which will render the
		// Products
		this.getServletContext().getRequestDispatcher("/Recipes.jsp").forward(request, response);

	}
}
